#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <stdint.h>

#include "sqlite3.h"
#include "drv_db_column.h"

/***************************************************************
* Name:   prepare_insert_stmt()
* Input : db 数据库 table_name 表名 columns 数据信息 columns_count 信息长度
* Output: void 
* Return: 生成的处理语句 
* Author: heweilong
* Revise: V1.2
* Description: 初始化添加数据预处理语句（支持批量操作）
***************************************************************/
static sqlite3_stmt* prepare_insert_stmt(	sqlite3* db, const char* table_name,
																					const db_column_value_t* columns, size_t columns_count)
{
	/*输入数据 有效性判断 放在业务主函数中 */

	/*构建动态SQL*/
	size_t cols_len = columns_count * 64; // 预估每列平均长度
	size_t ph_len = columns_count * 2;
	char* cols = calloc(1, cols_len);
	if(cols == NULL)
	{
		DB_DB_LOG_ERROR("calloc cols fail\n");
		return NULL;
	}
	char* placeholders = calloc(1, ph_len);
	if(placeholders == NULL)
	{
		DB_DB_LOG_ERROR("calloc placeholders fail\n");
		free(cols);
		return NULL;
	}

	for (int i = 0; i < columns_count; i++)
	{
		strcat(cols, columns[i].column_name);
		strcat(placeholders, "?");
		if (i < columns_count - 1)
		{
			strcat(cols, ", ");
			strcat(placeholders, ", ");
		}
	}

	char sql_stmt[] = "INSERT INTO %s (%s) VALUES (%s)";
	int sql_len = snprintf(NULL, 0, sql_stmt, table_name, cols, placeholders) + 1;
	char* sql = malloc(sql_len);
	if(sql == NULL)
	{
		DB_DB_LOG_ERROR("malloc sql fail\n");
		free(cols);
		free(placeholders);
		return NULL;
	}
	snprintf(sql, sql_len, sql_stmt, table_name, cols, placeholders);

	// 准备语句
	sqlite3_stmt* stmt = NULL;
	if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK)
	{
		/*准备失败 释放空间*/
		DB_ERROR(db);
		DB_SAFE_FINALIZE(stmt);
	}

	/*准备成功 释放空间*/
	free(cols);
	free(placeholders);
	free(sql);
	return stmt;
}

/***************************************************************
* Name:   prepare_delete_stmt()
* Input : db 数据库 table_name 表名 cond 条件数组 cond_count 条件数量
* Output: void 
* Return: 生成的处理语句 
* Author: heweilong
* Revise: V1.3
* Description: 支持逻辑操作符的预处理语句生成
***************************************************************/
static sqlite3_stmt* prepare_delete_stmt(	sqlite3* db, const char* table_name,
																					const db_where_condition_t* cond, size_t cond_count)
{
	/*输入数据 有效性判断 放在业务主函数中 */

	/* 构建动态WHERE子句 */
	char where_clause[1024] = {0};
	if(cond_count > 0)
	{
		for (size_t i = 0; i < cond_count; i++)
		{
			const db_where_condition_t* this_cond = &cond[i];
	
			// 获取比较运算符字符串
			const char* op_str = db_get_operator_str(this_cond->cmp_op);
			if (!op_str)
			{
				DB_DB_LOG_ERROR("Invalid comparison operator at condition %zu %x\n", i, this_cond->cmp_op);
				return NULL;
			}
	
			/* 第二个条件开始 添加逻辑操作符 */
			if (i > 0)
			{
				switch (this_cond->logic_op)
				{
					case LOGIC_AND: 
					{
						strcat(where_clause, " AND ");
						break;
					}
					case LOGIC_OR:
					{
						strcat(where_clause, " OR ");
						break;
					}
					default:
					{
						printf("Invalid logic operator at condition %zu\n", i);
						return NULL;
					}
				}
			}
	
			/* 处理NOT操作符 */
			if (this_cond->is_not)
			{
				strcat(where_clause, "NOT ");
			}
	
			/* 构建这个条件的表达式 */
			char condition[128] = {0};
			snprintf(condition, sizeof(condition), "%s %s ?", this_cond->value.column_name, op_str);
			strcat(where_clause, condition);
		}
	}
	else
	{
		strcat(where_clause, "1 = 1");
	}
	/* 构建完整SQL */
	char sql_stmt[] = "DELETE FROM %s WHERE %s";
	int sql_len = snprintf(NULL, 0, sql_stmt, table_name, where_clause) + 1;
	char* sql = malloc(sql_len);
	if(sql == NULL)
	{
		DB_DB_LOG_ERROR("malloc sql fail\n");
	}
	snprintf(sql, sql_len, sql_stmt, table_name, where_clause);

	/* 准备语句 */
	sqlite3_stmt* stmt = NULL;
	if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK)
	{
		DB_ERROR(db);
		DB_SAFE_FINALIZE(stmt);
	}

	free(sql);

	return stmt;
}

/***************************************************************
* Name:   prepare_update_stmt()
* Input : db 数据库 table_name 表名 param 更新参数
* Output: void 
* Return: 预处理语句
* Author: heweilong
* Revise: V1.2
* Description: 生成UPDATE预处理语句
***************************************************************/
static sqlite3_stmt* prepare_update_stmt(	sqlite3* db, const char* table_name,
																					const db_update_param* param)
{
	/*输入数据 有效性判断 放在业务主函数中 */

	/* 构建SET子句 */
	char set_clause[512] = {0};
	for (size_t i = 0; i < param->set_count; i++)
	{
		strcat(set_clause, param->set_columns[i].column_name);
		strcat(set_clause, " = ?");
		if (i < param->set_count - 1)
		{
			strcat(set_clause, ", ");
		}
	}

	/* 构建WHERE子句 */
	char where_clause[512] = {0};
	if(param->condition_count > 0)
	{
		for (size_t i = 0; i < param->condition_count; i++)
		{
			const db_where_condition_t* cond = &param->conditions[i];
	
			// 获取比较运算符字符串
			const char* op_str = db_get_operator_str(cond->cmp_op);
			if (!op_str)
			{
				DB_DB_LOG_ERROR("Invalid comparison operator at condition %zu %x\n", i, cond->cmp_op);
				return NULL;
			}

			/* 添加逻辑运算符 */
			if (i > 0)
			{
				switch (cond->logic_op)
				{
					case LOGIC_AND:
					{
						strcat(where_clause, " AND "); 
						break;
					}
					case LOGIC_OR:
					{
						strcat(where_clause, " OR ");
						break;
					}
					default:
					{
						DB_DB_LOG_ERROR("Invalid logic operator at condition %zu\n", i);
						return NULL;
					}
				}
			}
	
			/* 处理NOT */
			if (cond->is_not)
			{
				strcat(where_clause, "NOT ");
			}
	
			/* 添加条件表达式 */
			char cond_str[128] = {0};
			snprintf(cond_str, sizeof(cond_str), "%s %s ?", cond->value.column_name, op_str);
			strcat(where_clause, cond_str);
		}
	}
	else
	{
		return NULL;
	}

	/* 构建完整SQL */
	char* sql = NULL;
	char sql_stmt[] = "UPDATE %s SET %s WHERE %s";
	int sql_len = snprintf(NULL, 0, sql_stmt, table_name, set_clause, where_clause) + 1;
	sql = malloc(sql_len);
	if(sql == NULL)
	{
		DB_DB_LOG_ERROR("malloc sql fail\n");
	}
	snprintf(sql, sql_len, sql_stmt, table_name, set_clause, where_clause);

	/* 准备语句 */
	sqlite3_stmt* stmt = NULL;
	if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK)
	{
		DB_ERROR(db);
		DB_SAFE_FINALIZE(stmt);
	}
	
	free(sql);

	return stmt;
}

/***************************************************************
* Name:   prepare_select_stmt()
* Input : db 数据库 table_name 表名 param 查询参数
* Return: 预处理语句
* Author: heweilong
* Revise: V1.1
* Description: 生成SELECT预处理语句
***************************************************************/
static sqlite3_stmt* prepare_select_stmt(	sqlite3* db, const char* table_name,
																					const db_select_param* param)
{
	/* 构建SELECT列列表 */
	char columns_list[512] = {0};
	for (size_t i = 0; i < param->column_count; i++)
	{
		if (!db_is_valid_identifier(param->select_columns[i]))
		{
			DB_DB_LOG_ERROR("Invalid column name: %s\n", param->select_columns[i]);
			return NULL;
		}
		strcat(columns_list, param->select_columns[i]);
		if (i < param->column_count - 1)
		{
			strcat(columns_list, ", ");
		}
	}

	/* 构建WHERE子句 */
	char where_clause[512] = {0};
	if(param->condition_count != 0)
	{
		for (size_t i = 0; i < param->condition_count; i++)
		{
			const db_where_condition_t* cond = &param->conditions[i];
			
			if (i > 0)
			{
				switch (cond->logic_op)
				{
					case LOGIC_AND:
					{
						strcat(where_clause, " AND ");
						break;
					}
					case LOGIC_OR:
					{
						strcat(where_clause, " OR ");
						break;
					}
					default:
					{
						return NULL;
					}
				}
			}

			if (cond->is_not) 
			{
				strcat(where_clause, "NOT ");
			}

			char cond_str[128] = {0};
			snprintf(cond_str, sizeof(cond_str), "%s %s ?", cond->value.column_name, db_get_operator_str(cond->cmp_op));
			strcat(where_clause, cond_str);
		}
	}
	else
	{
		strcat(where_clause, "1 = 1");
	}

	/* 构建完整SQL */
	char* sql = NULL;
	const char sql_stmt[] = "SELECT %s FROM `%s` WHERE %s";
	int sql_len = snprintf(NULL, 0, sql_stmt, columns_list, table_name, where_clause) + 1;
	sql = malloc(sql_len);
	snprintf(sql, sql_len, sql_stmt, columns_list, table_name, where_clause);// 添加反引号转义

	/* 准备语句 */
	sqlite3_stmt* stmt = NULL;
	if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK)
	{
		DB_ERROR(db);
		DB_SAFE_FINALIZE(stmt);
	}

	free(sql);

	return stmt;
}

/***************************************************************
* Name:   insert_operation()
* Input : db 数据库 table_name 插入数据的表 data 插入的一行数据
* Output: void 
* Return: 合格 true
* Author: heweilong
* Revise: V1.3
* Description: 数据插入操作
***************************************************************/
int insert_operation(sqlite3* db, const char* table_name, const void* data)
{
	/*输入数据 有效性判断 放在业务主函数中 */

	const db_line_col_t* batch = (db_line_col_t*)data;
	
	sqlite3_stmt* stmt = prepare_insert_stmt(db, table_name, batch->col, batch->col_count);
	if (!stmt)
	{
		/*准备失败直接退出*/
		return SQLITE_ERROR;
	}

	/*绑定数据*/
	for (int i = 0; i < batch->col_count; i++)
	{
		/*绑定数据信息*/
		const db_column_value_t* col = &batch->col[i];
		int idx = i + 1;	// SQLite参数索引从1开始

		switch (col->data_type)
		{
			case SQLITE_INTEGER:
			{
				if(sqlite3_bind_int(stmt, idx, col->value.int_value) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("INSERT NO%d NAME:%s type:SQLITE_INTEGER bind fail\n", i, col->column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return SQLITE_ERROR;
				}
				break;
			}
			case SQLITE_FLOAT:
			{
				if(sqlite3_bind_double(stmt, idx, col->value.float_value) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("INSERT NO%d NAME:%s type:SQLITE_FLOAT bind fail\n", i, col->column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return SQLITE_ERROR;
				}
				break;
			}
			case SQLITE_TEXT:
			{
				if(sqlite3_bind_text(stmt, idx, col->value.text_value, -1, SQLITE_TRANSIENT) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("INSERT NO%d NAME:%s type:SQLITE_TEXT bind fail\n", i, col->column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return SQLITE_ERROR;
				}
				break;
			}
			case SQLITE_BLOB:
			{
				if(sqlite3_bind_blob(	stmt, idx,
															col->value.blob_value.data, col->value.blob_value.size,
															SQLITE_TRANSIENT) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("INSERT NO%d NAME:%s type:SQLITE_BLOB bind fail\n", i, col->column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return SQLITE_ERROR;
				}
				break;
			}
			case SQLITE_NULL:
			{
				if(sqlite3_bind_null(stmt, idx) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("INSERT NO%d NAME:%s type:SQLITE_BLOB bind fail\n", i, col->column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return SQLITE_ERROR;
				}
				break;
			}
			default:	/*异常类型*/
			{
				DB_DB_LOG_ERROR("INSERT Unknown data type: %d\n", col->data_type);
				/*释放语句内存*/
				DB_SAFE_FINALIZE(stmt);
				return SQLITE_ERROR;
			}
		}
	}

	/*执行语句*/
	if (sqlite3_step(stmt) != SQLITE_DONE)
	{
		/*执行失败 释放空间*/
		DB_ERROR(db);
		DB_SAFE_FINALIZE(stmt);
		return SQLITE_ERROR;
	}
	else
	{
		/*执行成功 释放空间*/
		DB_SAFE_FINALIZE(stmt);
		return SQLITE_OK;
	}
}

/***************************************************************
* Name:   delete_operation()
* Input : db 数据库 table_name 表名 data 删除条件
* Output: void 
* Return: SQLITE操作结果
* Author: heweilong
* Revise: V1.2
* Description: 支持复杂条件的删除操作
***************************************************************/
int delete_operation(sqlite3* db, const char* table_name, const void* data)
{
	/*输入数据 有效性判断 放在业务主函数中 */

	const db_col_delete_param_t* batch = (const db_col_delete_param_t*)data;
	
	/* 生成预处理语句 */
	sqlite3_stmt* stmt = prepare_delete_stmt(db, table_name, batch->param, batch->param_count);
	if (!stmt)
	{
		/*准备失败直接退出*/
		return SQLITE_ERROR;
	}

	/* 绑定参数 */
	for (int i = 0; i < batch->param_count; i++)
	{
		/*绑定条件信息*/
		const db_where_condition_t* cond = &batch->param[i];
		int idx = i + 1; // SQLite参数索引从1开始

		switch (cond->value.data_type)
		{
			case SQLITE_INTEGER:
			{
				if(sqlite3_bind_int(stmt, idx, cond->value.value.int_value) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("DELETE NO%d NAME:%s type:SQLITE_INTEGER bind fail\n", i, cond->value.column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return SQLITE_ERROR;
				}
				break;
			}
			case SQLITE_FLOAT:
			{
				if(sqlite3_bind_double(stmt, idx, cond->value.value.float_value) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("DELETE NO%d NAME:%s type:SQLITE_FLOAT bind fail\n", i, cond->value.column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return SQLITE_ERROR;
				}
				break;
			}
			case SQLITE_TEXT:
			{
				if(sqlite3_bind_text(stmt, idx, cond->value.value.text_value, -1, SQLITE_TRANSIENT) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("DELETE NO%d NAME:%s type:SQLITE_TEXT bind fail\n", i, cond->value.column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return SQLITE_ERROR;
				}
				break;
			}
			case SQLITE_BLOB:
			{
				if(sqlite3_bind_blob(	stmt, idx,
															cond->value.value.blob_value.data, cond->value.value.blob_value.size, 
															SQLITE_TRANSIENT) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("DELETE NO%d NAME:%s type:SQLITE_BLOB bind fail\n", i, cond->value.column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return SQLITE_ERROR;
				}
				break;
			}
			case SQLITE_NULL:
			{
				if(sqlite3_bind_null(stmt, idx) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("DELETE NO%d NAME:%s type:SQLITE_NULL bind fail\n", i, cond->value.column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return SQLITE_ERROR;
				}
				break;
			}
			default:	/*异常类型*/
			{
				DB_DB_LOG_ERROR("DELETE Unknown data type at condition %d\n", i);
				/*释放语句内存*/
				DB_SAFE_FINALIZE(stmt);
				return SQLITE_ERROR;
			}
		}
	}

	/*执行语句*/
	if (sqlite3_step(stmt) != SQLITE_DONE)
	{
		/*执行失败 释放空间*/
		DB_ERROR(db);
		DB_SAFE_FINALIZE(stmt);
		return SQLITE_ERROR;
	}
	else
	{
		/*执行成功 释放空间*/
		DB_SAFE_FINALIZE(stmt);
		return SQLITE_OK;
	}
}

/***************************************************************
* Name:   update_operation()
* Input : db 数据库 table_name 表名 data 更新参数
* Return: SQLITE操作结果
* Author: heweilong
* Revise: V1.1
* Description: 执行更新操作
***************************************************************/
static int update_operation(sqlite3* db, const char* table_name, const void* data)
{
	/*输入数据 有效性判断 放在业务主函数中 */

	const db_update_param* param = (const db_update_param*)data;
	
	sqlite3_stmt* stmt = prepare_update_stmt(db, table_name, param);
	if (!stmt)
	{
		return SQLITE_ERROR;
	}

	/* 绑定参数 */
	int bind_idx = 1;  // SQLite参数索引从1开始

	/* 绑定SET参数 */
	for (size_t i = 0; i < param->set_count; i++)
	{
		const db_column_value_t* col = &param->set_columns[i];
		
		switch (col->data_type)
		{
			case SQLITE_INTEGER:
			{
				if(sqlite3_bind_int(stmt, bind_idx++, col->value.int_value) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("UPDATE SET NO%d NAME:%s type:SQLITE_INTEGER bind fail\n", bind_idx - 1, col->column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return SQLITE_ERROR;
				}
				break;
			}
			case SQLITE_FLOAT:
			{
				if(sqlite3_bind_double(stmt, bind_idx++, col->value.float_value) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("UPDATE SET NO%d NAME:%s type:SQLITE_FLOAT bind fail\n", bind_idx - 1, col->column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return SQLITE_ERROR;
				}
				break;
			}
			case SQLITE_TEXT:
			{
				if(sqlite3_bind_text(stmt, bind_idx++, col->value.text_value, -1, SQLITE_TRANSIENT) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("UPDATE SET NO%d NAME:%s type:SQLITE_TEXT bind fail\n", bind_idx - 1, col->column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return SQLITE_ERROR;
				}
				break;
			}
			case SQLITE_BLOB:
			{
				if(sqlite3_bind_blob(stmt, bind_idx++, col->value.blob_value.data, col->value.blob_value.size, SQLITE_TRANSIENT) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("UPDATE SET NO%d NAME:%s type:SQLITE_BLOB bind fail\n", bind_idx - 1, col->column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return SQLITE_ERROR;
				}
				break;
			}
			case SQLITE_NULL:
			{
				if(sqlite3_bind_null(stmt, bind_idx++) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("UPDATE SET NO%d NAME:%s type:SQLITE_NULL bind fail\n", bind_idx - 1, col->column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return SQLITE_ERROR;
				}
				break;
			}
			default:
			{
				DB_DB_LOG_ERROR("UPDATE SET  NO%d Invalid SET data type: %d\n", bind_idx, col->data_type);
				sqlite3_finalize(stmt);
				return SQLITE_ERROR;
			}
		}
	}

	/* 绑定WHERE参数 */
	for (size_t i = 0; i < param->condition_count; i++)
	{
		const db_where_condition_t* cond = &param->conditions[i];

		switch (cond->value.data_type)
		{
			case SQLITE_INTEGER:
			{
				if(sqlite3_bind_int(stmt, bind_idx++, cond->value.value.int_value) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("UPDATE WHERE NO%d NAME:%s type:SQLITE_INTEGER bind fail\n", bind_idx - 1, cond->value.column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return SQLITE_ERROR;
				}
				break;
			}
			case SQLITE_FLOAT:
			{
				if(sqlite3_bind_double(stmt, bind_idx++, cond->value.value.float_value) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("UPDATE WHERE NO%d NAME:%s type:SQLITE_FLOAT bind fail\n", bind_idx - 1, cond->value.column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return SQLITE_ERROR;
				}
				break;
			}
			case SQLITE_TEXT:
			{
				if(sqlite3_bind_text(stmt, bind_idx++, cond->value.value.text_value, -1, SQLITE_TRANSIENT) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("UPDATE WHERE NO%d NAME:%s type:SQLITE_TEXT bind fail\n", bind_idx - 1, cond->value.column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return SQLITE_ERROR;
				}
				break;
			}
			case SQLITE_BLOB:
			{
				if(sqlite3_bind_blob(stmt, bind_idx++,
					cond->value.value.blob_value.data, cond->value.value.blob_value.size,
					SQLITE_TRANSIENT) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("UPDATE WHERE NO%d NAME:%s type:SQLITE_BLOB bind fail\n", bind_idx - 1, cond->value.column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return SQLITE_ERROR;
				}
				break;
			}
			case SQLITE_NULL:
			{
				if(sqlite3_bind_null(stmt, bind_idx++) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("UPDATE WHERE NO%d NAME:%s type:SQLITE_NULL bind fail\n", bind_idx - 1, cond->value.column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return SQLITE_ERROR;
				}
				break;
			}
			default:
			{
				DB_DB_LOG_ERROR("UPDATE WHERE NO%d Invalid WHERE data type: %d\n", bind_idx , cond->value.data_type);
				sqlite3_finalize(stmt);
				return SQLITE_ERROR;
			}
		}
	}

	/* 执行更新 */
	if (sqlite3_step(stmt) != SQLITE_DONE)
	{
		/*执行失败 释放空间*/
		DB_ERROR(db);
		DB_SAFE_FINALIZE(stmt);
		return SQLITE_ERROR;
	}
	else
	{
		/*执行成功 释放空间*/
		DB_SAFE_FINALIZE(stmt);
		return SQLITE_OK;
	}
}

/***************************************************************
* Name:   fetch_row_data()
* Input : stmt 预处理语句 param 查询参数
* Output: void 
* Return: 单行结果数据
* Author: heweilong
* Revise: V1.2
* Description: 提取单行数据到结构体
***************************************************************/
static db_result_node* fetch_row_data(sqlite3_stmt* stmt, const db_select_param* param)
{
	/*动态创建一个队列项 并法初始化*/
	db_result_node* node = calloc(1, sizeof(db_result_node));
	if(node == NULL)
	{
		DB_DB_LOG_ERROR("node calloc failed \r\n");
		return NULL;
	}
	/*设置 队列项数*/
	node->column_count = param->column_count;
	node->columns = calloc(param->column_count, sizeof(db_column_value_t));
	if(node->columns == NULL)
	{
		DB_DB_LOG_ERROR("node->columns calloc failed \r\n");
		free(node);
		return NULL;
	}

	for (size_t i = 0; i < param->column_count; i++)
	{
		/*获取数据名 和 数据类型*/
		const char* col_name = param->select_columns[i];
		size_t name_len = strlen(col_name) + 1;
		node->columns[i].column_name = calloc(name_len, sizeof(char));
		strncpy(node->columns[i].column_name, col_name, name_len);
    node->columns[i].column_name[name_len - 1] = '\0';

		int col_type = sqlite3_column_type(stmt, i);
		node->columns[i].data_type = col_type;

		switch (col_type)
		{
			case SQLITE_INTEGER:
			{
				node->columns[i].value.int_value = sqlite3_column_int(stmt, i);
				break;
			}
			case SQLITE_FLOAT:
			{
				node->columns[i].value.float_value = sqlite3_column_double(stmt, i);
				break;
			}
			case SQLITE_TEXT:
			{
				/*获取字符串数据 和 数据长度*/
				const char* text = (const char*)sqlite3_column_text(stmt, i);
				size_t len = sqlite3_column_bytes(stmt, i);
				node->columns[i].value.text_value = strndup(text, len);
				break;
			}
			case SQLITE_BLOB:
			{
				/*获取二进制数据 和 数据长度*/
				const void* blob = sqlite3_column_blob(stmt, i);
				size_t size = sqlite3_column_bytes(stmt, i);
				node->columns[i].value.blob_value.data = malloc(size);
				memcpy(node->columns[i].value.blob_value.data, blob, size);
				node->columns[i].value.blob_value.size = size;
				break;
			}
			case SQLITE_NULL:
			{
				node->columns[i].value.text_value = NULL;
				break;
			}
		}
	}

	return node;
}

/***************************************************************
* Name:   query_operation()
* Input : db 数据库 table_name 表名 data 查询参数
* Return: 结果队列指针
* Author: heweilong
* Revise: V1.1
* Description: 执行查询操作
***************************************************************/
static db_result_queue* query_operation(sqlite3* db, const char* table_name, const void* data)
{
	/*输入数据 有效性判断 放在业务主函数中 */

	const db_select_param* param = (const db_select_param*)data;

	/* 生成预处理语句 */
	sqlite3_stmt* stmt = prepare_select_stmt(db, table_name, param);
	if (!stmt)
	{
		return NULL;
	}

	/* 绑定WHERE参数 */
	for (size_t i = 0; i < param->condition_count; i++)
	{
		const db_where_condition_t* cond = &param->conditions[i];
		int idx = i + 1;

		switch (cond->value.data_type)
		{
			case SQLITE_INTEGER:
			{
				if(sqlite3_bind_int(stmt, idx, cond->value.value.int_value) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("SELECT NO%d NAME:%s type:SQLITE_INTEGER bind fail\n", idx - 1, cond->value.column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return NULL;
				}
				break;
			}
			case SQLITE_FLOAT:
			{
				if(sqlite3_bind_double(stmt, idx, cond->value.value.float_value) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("SELECT NO%d NAME:%s type:SQLITE_FLOAT bind fail\n", idx - 1, cond->value.column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return NULL;
				}
				break;
			}
			case SQLITE_TEXT:
			{
				if(sqlite3_bind_text(stmt, idx, cond->value.value.text_value, -1, SQLITE_TRANSIENT) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("SELECT NO%d NAME:%s type:SQLITE_TEXT bind fail\n", idx - 1, cond->value.column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return NULL;
				}
				break;
			}
			case SQLITE_BLOB:
			{
				if(sqlite3_bind_blob(stmt, idx, cond->value.value.blob_value.data, cond->value.value.blob_value.size, SQLITE_TRANSIENT) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("SELECT NO%d NAME:%s type:SQLITE_BLOB bind fail\n", idx - 1, cond->value.column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return NULL;
				}
				break;
			}
			case SQLITE_NULL:
			{
				if(sqlite3_bind_null(stmt, idx) != SQLITE_OK)
				{
					DB_DB_LOG_ERROR("SELECT NO%d NAME:%s type:SQLITE_NULL bind fail\n", idx - 1, cond->value.column_name);
					/*释放语句内存*/
					DB_SAFE_FINALIZE(stmt);
					return NULL;
				}
				break;
			}
			default:	/*异常类型*/
			{
				DB_DB_LOG_ERROR("SELECT Unknown data type at condition %d\n", idx - 1);
				/*释放语句内存*/
				DB_SAFE_FINALIZE(stmt);
				return NULL;
			}
		}
	}

	/*结果存储空间*/
	db_result_queue* queue = calloc(1, sizeof(db_result_queue));
	if(queue == NULL)
	{
		DB_DB_LOG_ERROR("calloc queue fail\n");
		/*释放语句内存*/
		DB_SAFE_FINALIZE(stmt);
		return NULL;
	}

	/* 遍历结果集 */
	while (sqlite3_step(stmt) == SQLITE_ROW)
	{
		db_result_node* node = fetch_row_data(stmt, param);
		if (!node)
		{
			continue;
		}

		if (!queue->head)	//第一项数据
		{
			queue->head = queue->tail = node;
		}
		else	//第二项以及之后的数据 数据
		{
			queue->tail->next = node;
			queue->tail = node;
		}

		queue->count++;
	}

	/*释放使用内存*/
	DB_SAFE_FINALIZE(stmt);
	
	return queue;
}

/***************************************************************
* Name:   db_col_insert_data()
* Input : db 数据库 table_name 操作的表 data 插入数据
* Output: void 
* Return: SQLITE_OK 合格
* Author: heweilong
* Revise: V1.3
* Description: 插入数据主函数
***************************************************************/
int db_col_insert_data(sqlite3* db, const char* table_name, const db_col_insert_param_t data)
{
	/* 参数校验 */
	if(db == NULL)	//数据库指针判断
	{
		DB_DB_LOG_ERROR("db = null\n");
		return SQLITE_ERROR;
	}
	else if(table_name == NULL)	//表名判断
	{
		DB_DB_LOG_ERROR("table_name = null\n");
		return SQLITE_ERROR;
	}
	else if (!db_is_valid_identifier(table_name))	//验证表名和列名 是否规范
	{
		DB_DB_LOG_ERROR("Invalid table name: %s\n", table_name);
		return SQLITE_ERROR;
	}
	else if(data.insert_data == NULL)	//插入数据判断
	{
		DB_DB_LOG_ERROR("insert_data = null\n");
		return SQLITE_ERROR;
	}
	else if(data.data_count == 0)			//插入数据数量判断
	{
		DB_DB_LOG_ERROR("insert_data count = 0\n");
		return SQLITE_ERROR;
	}
	else
	{
		/*验证数据列名 是否规范*/
		for (int i = 0; i < data.data_count; i++)
		{
			for(int j = 0; j < data.insert_data[i].col_count; j++)
			{
				if (!data.insert_data[i].col[j].column_name ||
						!db_is_valid_identifier(data.insert_data[i].col[j].column_name))
				{
					DB_DB_LOG_ERROR(" data:%d col:%d Invalid column name: %s\n", i, j, data.insert_data[i].col[j].column_name);
					return SQLITE_ERROR;
				}
			}
		}
	}

	int ret = 0;
	for(int i = 0; i < data.data_count; i++)
	{
		ret |= db_transaction_wrapper(db, insert_operation, table_name, (void*)(data.insert_data + i));
	}

	return ret;
}

/***************************************************************
* Name:   db_col_insert_data()
* Input : db 数据库 table_name 操作的表 data 插入数据
* Output: void 
* Return: SQLITE_OK 合格
* Author: heweilong
* Revise: V1.2
* Description: 删除数据
***************************************************************/
int db_col_delete_data(sqlite3* db, const char* table_name, db_col_delete_param_t param)
{
	/* 参数校验 */
	if(db == NULL)
	{
		DB_DB_LOG_ERROR("db = null\n");
		return SQLITE_ERROR;
	}
	else if(table_name == NULL)
	{
		DB_DB_LOG_ERROR("table_name = null\n");
		return SQLITE_ERROR;
	}
	else if (!db_is_valid_identifier(table_name))	//验证表名和列名 是否规范
	{
		DB_DB_LOG_ERROR("Invalid table name: %s\n", table_name);
		return SQLITE_ERROR;
	}
	else if (param.param == NULL)
	{
		DB_DB_LOG_ERROR("param.param == NULL\n");
		return SQLITE_ERROR;
	}
	else if (param.param_count == 0)
	{
		DB_DB_LOG_ERROR("param.param_count = null\n");
		return SQLITE_ERROR;
	}
	else
	{
		for(int i = 0; i < param.param_count; i++)
		{
			if (!param.param[i].value.column_name ||
					!db_is_valid_identifier(param.param[i].value.column_name))
			{
				DB_DB_LOG_ERROR("param:%d Invalid column name: %s\n", i, param.param[i].value.column_name);
				return SQLITE_ERROR;
			}
		}
	}

	return db_transaction_wrapper(db, delete_operation, table_name, (void*)(&param));
}

/***************************************************************
* Name:   db_col_insert_data()
* Input : db 数据库 table_name 表名 param 更新参数
* Output: void 
* Return: SQLITE_OK 合格
* Author: heweilong
* Revise: V1.2
* Description: 更新数据
***************************************************************/
int db_col_update_data(sqlite3* db, const char* table_name, db_update_param param)
{
	/* 参数校验 */
	if(db == NULL)
	{
		DB_DB_LOG_ERROR("db = null\n");
		return SQLITE_ERROR;
	}
	else if(table_name == NULL)
	{
		DB_DB_LOG_ERROR("table_name = null\n");
		return SQLITE_ERROR;
	}
	else if (!db_is_valid_identifier(table_name))	//验证表名和列名 是否规范
	{
		DB_DB_LOG_ERROR("Invalid table name: %s\n", table_name);
		return SQLITE_ERROR;
	}
	else if (param.set_count == 0)
	{
		DB_DB_LOG_ERROR("param.set_count == NULL\n");
		return SQLITE_ERROR;
	}
	else if (param.condition_count == 0)
	{
		DB_DB_LOG_ERROR("param.condition_count == NULL\n");
		return SQLITE_ERROR;
	}
	else
	{
		for(int i = 0; i < param.set_count; i++)
		{
			if (!param.set_columns[i].column_name ||
				!db_is_valid_identifier(param.set_columns[i].column_name))
			{
				DB_DB_LOG_ERROR("COL param:%d Invalid column name: %s\n", i, param.set_columns[i].column_name);
				return SQLITE_ERROR;
			}
		}

		for(int i = 0; i < param.condition_count; i++)
		{
			if (!param.conditions[i].value.column_name ||
				!db_is_valid_identifier(param.conditions[i].value.column_name))
			{
				DB_DB_LOG_ERROR("COND param:%d Invalid column name: %s\n", i, param.conditions[i].value.column_name);
				return SQLITE_ERROR;
			}
		}
	}

	return db_transaction_wrapper(db, update_operation, table_name, (void*)(&param));
}

/***************************************************************
* Name:   db_col_query_data()
* Input : db 数据库 table_name 表名 select_columns 选择的列名 col_count 选择的列数量 conditions 选择条件 cond_count 条件数量
* Output: void 
* Return: SQLITE_OK 合格
* Author: heweilong
* Revise: V1.2
* Description: 查询数据
***************************************************************/
db_result_queue* db_col_query_data(sqlite3* db, const char* table_name, db_select_param param)
{
	/* 参数校验 */
	if(db == NULL)
	{
		DB_DB_LOG_ERROR("db = null\n");
		return NULL;
	}
	else if(table_name == NULL)
	{
		DB_DB_LOG_ERROR("table_name = null\n");
		return NULL;
	}
	else if (!db_is_valid_identifier(table_name))	//验证表名和列名 是否规范
	{
		DB_DB_LOG_ERROR("Invalid table name: %s\n", table_name);
		return NULL;
	}
	else if (param.column_count == 0)
	{
		DB_DB_LOG_ERROR("param.column_count == 0\n");
		return NULL;
	}
	else if (param.select_columns == NULL)
	{
		DB_DB_LOG_ERROR("param.select_columns == NULL\n");
		return NULL;
	}
	else
	{
		for(int i = 0; i < param.column_count; i++)
		{
			if (!param.select_columns[i] ||
					!db_is_valid_identifier(param.select_columns[i]))
			{
				DB_DB_LOG_ERROR("COL param:%d Invalid column name: %s\n", i, param.select_columns[i]);
				return NULL;
			}
		}
	}

	return query_operation(db, table_name, &param);
}

/***************************************************************
* Name:   db_col_select_res_free()
* Input : queue 结果队列
* Output: void 
* Return: void
* Author: heweilong
* Revise: V1.2
* Description: 释放结果队列内存
***************************************************************/
void db_col_select_res_free(db_result_queue* queue)
{
	db_result_node* current = queue->head;
	while (current)
	{
		db_result_node* next = current->next;
		
		/*释放当前项的数据申请的存储空间*/
		for (size_t i = 0; i < current->column_count; i++)
		{
			/*释放列名内存*/
			if (current->columns[i].column_name)
			{
				free(current->columns[i].column_name);
			}
			/*释放列数据内存*/
			if (current->columns[i].data_type == SQLITE_TEXT)
			{
				free(current->columns[i].value.text_value);
			}
			else if (current->columns[i].data_type == SQLITE_BLOB)
			{
				free(current->columns[i].value.blob_value.data);
			}
		}
		/*释放当前项的数据*/
		free(current->columns);
		/*释放当前项*/
		free(current);

		/*切换到下一项*/
		current = next;
	}

	/*释放队列*/
	free(queue);
}

/***************************************************************
* Name:   printf_node_info()
* Input : node 结果节点
* Output: void 
* Return: void
* Author: heweilong
* Revise: V1.1
* Description: 打印节点信息
***************************************************************/
void printf_node_info(db_result_node* node)
{
	for(int i = 0; i < node->column_count; i++)
	{
		db_column_value_t * col = node->columns + i;
		switch (col->data_type)
		{
			case SQLITE_INTEGER:
			{
				printf("%s:%d\r\n", col->column_name, col->value.int_value);
				break;
			}
			case SQLITE_FLOAT:
			{
				printf("%s:%f\r\n", col->column_name, col->value.float_value);
				break;
			}
			case SQLITE_TEXT:
			{
				printf("%s:%s\r\n", col->column_name, col->value.text_value);
				break;
			}
			default:
			{
				printf("no def type:%d\r\n", node->columns[i].data_type);
				break;
			}
		}
	}
}